package com.si.controller.web;

import org.apache.commons.io.FileUtils;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.si.entity.FileDownload;
import com.si.service.FileDownloadService;
import com.si.util.Paging;
import com.si.util.QueryWhere;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

/**
 * 下载专区
 * @author Dell
 *
 */
@Controller
@RequestMapping("/fileDownload")
public class FileDownloadController {

	@Autowired
	private FileDownloadService fileDownloadService;
	
	/**
	 * 下载专区主页
	 * @return
	 */
	@RequestMapping
	public String load(ModelMap modelMap,
			@RequestParam(value = "curPage", defaultValue = "0", required = false) Integer curPage,
			@RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize) {
		QueryWhere.setOrderList(Order.desc("createDate"));
		Paging<FileDownload> paging = fileDownloadService.createCriteriaPaging(curPage, pageSize);
		modelMap.put("paging", paging);
		return "webPage/fileDownload/list";
	}



	@RequestMapping(value = "/download/{id}", method = RequestMethod.GET) //匹配的是href中的download请求
	public ResponseEntity<byte[]> download(HttpServletRequest request, @PathVariable(value = "id") Integer id,
										   Model model, HttpSession session) throws IOException {

		//String downloadFilePath = "D:\\userUploadFile\\Files";//从我们的上传文件夹中去取
		FileDownload fileDownload = (FileDownload) fileDownloadService.getObjectById(id);
		String downloadFilePath = fileDownload.getAddress();
		//获取文件路径
		String path = session.getServletContext().getRealPath("/upload/fileDownload/");
		System.out.println(path);
		//获得要下载的File对象
		File file = new File(path + File.separator + downloadFilePath);
		HttpHeaders headers = new HttpHeaders();//http头信息
		String downloadFileName = new String(downloadFilePath.getBytes("UTF-8"), "iso-8859-1");//设置编码
		headers.setContentDispositionFormData("attachment", downloadFileName);
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		//MediaType:互联网媒介类型  contentType：具体请求中的媒体类型信息
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);

	}
}
